package org.myproject.persistence;

import org.hibernate.event.PreInsertEvent;
import org.hibernate.event.PreInsertEventListener;
import org.hibernate.event.PreUpdateEvent;
import org.hibernate.event.PreUpdateEventListener;
import org.myproject.persistence.event.PersistenceEvent;
import org.springframework.context.ApplicationContext;

/**
 * Hibernate event listener that translates hibernate events into
 * {@link PersistenceEvent}s and broadcasts them to spring context
 * 
 * @author ivaynberg
 */
public class PersistenceEventBroadcaster implements PreUpdateEventListener,
		PreInsertEventListener {

	private static final long serialVersionUID = 1L;
	
	private final ApplicationContext applicationContext;

	public PersistenceEventBroadcaster(ApplicationContext applicationContext) {
		if (applicationContext == null) {
			throw new IllegalArgumentException(
					"Applciation context cannot be null");
		}
		this.applicationContext = applicationContext;
	}

	public boolean onPreInsert(PreInsertEvent event) {
		applicationContext
				.publishEvent(new org.myproject.persistence.event.PreInsertEvent(
						event.getSource(), event.getEntity(), event.getId(),
						event.getPersister(), event.getState()));
		return false;
	}

	public boolean onPreUpdate(PreUpdateEvent event) {
		applicationContext
				.publishEvent(new org.myproject.persistence.event.PreUpdateEvent(
						event.getSource(), event.getEntity(), event.getId(),
						event.getPersister(), event.getOldState(), event
								.getState()));

		return false;
	}

}
